/*
This file is part of La Linea.

La Linea is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

La Linea is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with La Linea.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "FontManager.h"

FontManager* FontManager::_instance = NULL;

using namespace std;

FontManager::FontManager(void){}

FontManager::~FontManager(void){
	vector<FontType*>::iterator it = _fontTypes.begin();
	for(;it!=_fontTypes.end();it++) delete (*it);
	_fontTypes.clear();
}

FontManager* FontManager::getInstance(){
	if(_instance==NULL){
		_instance = new FontManager();
	}

	return _instance;
}

void FontManager::destroy(){
	delete _instance;
	_instance = NULL;
}

Font* FontManager::getFont(string name, int size){
	std::vector<FontType*>::iterator it = _fontTypes.begin();
	for(;it!=_fontTypes.end();it++){
		FontType* current = (*it);
		if(current->getName().compare(name) == 0) return (*it)->getFont(size);
	}

	FontType* newFont = new FontType(name);
	_fontTypes.push_back(newFont);
	return newFont->getFont(size);
}

void FontManager::write(Font& f, string text, Vector2f& pos){
	glPushMatrix();
	glLoadIdentity();

	Util::pushScreenCoordinateMatrix(); 

	float h=f._size/.63f;
	vector<string> lines;

	// Extract lines
	std::string currentLine;
	std::istringstream inputStream(text);
    while (getline(inputStream, currentLine))
    {
        if (!currentLine.empty())
            lines.push_back(currentLine);
    }
	
	glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT  | GL_ENABLE_BIT | GL_TRANSFORM_BIT); 
	glMatrixMode(GL_MODELVIEW);
	glDisable(GL_LIGHTING);
	glEnable(GL_TEXTURE_2D);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);      

	float modelview_matrix[16];     
	glGetFloatv(GL_MODELVIEW_MATRIX, modelview_matrix);

	for(unsigned int i=0;i<lines.size();i++) {
		glPushMatrix();
		glLoadIdentity();
		glTranslatef(pos.x,pos.y-h*i,0);
		glMultMatrixf(modelview_matrix);

		for(unsigned int j=0; j<lines[i].size(); j++){
			f.drawChar(lines[i].c_str()[j]);
		}

		glPopMatrix();
	}

	glPopAttrib();          

	Util::pop_projection_matrix();

	glPopMatrix();
}